from fastapi import APIRouter, Request, HTTPException
from pydantic import BaseModel, Field
from app.services.exchange_service import get_exchange_rate, calculate_exchange
from app.utils.response_handler import SuccessResponse
import logging
import traceback

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
router = APIRouter(prefix="/api/v1")


# 请求体模型
class ExchangeRateRequest(BaseModel):
    base_currency: str = Field(..., min_length=3, max_length=3, example="USD",
                               description="基准货币代码（3位字母，如USD）")
    target_currency: str = Field(..., min_length=3, max_length=3, example="CNY",
                                 description="目标货币代码（3位字母，如CNY）")


class ExchangeCalculationRequest(ExchangeRateRequest):
    base_price: float = Field(..., gt=0, example=100.0,
                              description="基准货币的金额，必须大于0")


@router.post("/exchange/rate", response_model=SuccessResponse)
async def get_rate(request: Request, req_data: ExchangeRateRequest):
    """获取两种货币之间的汇率"""
    try:
        client_ip = request.client.host
        headers = dict(request.headers)

        # 调用汇率服务
        result = get_exchange_rate(
            base_currency=req_data.base_currency,
            target_currency=req_data.target_currency
        )

        if not result["target_rate"]:
            raise HTTPException(status_code=404, detail="无法获取指定货币对的汇率")

        logging.info(
            f"汇率查询请求来自 {client_ip}, headers: {headers}, body: {req_data.dict()} 查询结果：{result}"
        )
        return SuccessResponse(data=result)

    except HTTPException:
        raise  # 重新抛出已定义的HTTP异常
    except Exception as e:
        logging.error(f"处理汇率查询请求出错: {e}\n{traceback.format_exc()}")
        raise HTTPException(
            status_code=500,
            detail=f"服务器内部错误: {str(e)}"
        )


@router.post("/exchange/calculate", response_model=SuccessResponse)
async def calculate(request: Request, req_data: ExchangeCalculationRequest):
    """计算货币转换后的金额"""
    try:
        client_ip = request.client.host
        headers = dict(request.headers)

        # 调用汇率计算服务
        result = calculate_exchange(
            base_currency=req_data.base_currency,
            target_currency=req_data.target_currency,
            base_price=req_data.base_price
        )

        if result["status"] == "失败":
            raise HTTPException(status_code=404, detail="货币转换失败，无法获取有效汇率")

        logging.info(
            f"汇率查询请求来自 {client_ip}, headers: {headers}, body: {req_data.dict()} 查询结果：{result}"
        )
        return SuccessResponse(data=result)

    except HTTPException:
        raise  # 重新抛出已定义的HTTP异常
    except Exception as e:
        logging.error(f"处理汇率计算请求出错: {e}\n{traceback.format_exc()}")
        raise HTTPException(
            status_code=500,
            detail=f"服务器内部错误: {str(e)}"
        )
